<?php

namespace app\models;

use yii\db\ActiveRecord;

class MemberCards extends ActiveRecord 
{

    /**
     * 判断卡号是否存在
     * @param $cardNum
     * @return bool
     */
    public static function exists($cardNum)
    {
        return self::find()
            ->where(array(
                'card_num' => $cardNum
            ))
            ->exists();
    }

    /**
     * 判断会员卡号是否合法
     * @param $card
     * @return bool
     */
    public static function isMember($card)
    {
        if (empty($card)) {
            return false;
        }

        $key = "card:{$card}";
        /** @var \Redis $redis */
        $redis = \Yii::$app->get('redis');
        $result = $redis->get($key);

        if ($result === false) {
            $row = self::findOne(array('card_num' => $card));

            if (empty($row)) {
                $result = 'false';
            } else {
                $result = 'true';
            }

            $redis->set($key, $result, 24 * 3600);
        }

        return $result == 'true';
    }

}